package com.bst.etl.service.impl;

import com.bst.common.annotation.DataSource;
import com.bst.common.constant.JobConstant;
import com.bst.common.core.domain.AjaxResult;
import com.bst.etl.mapper.DwQueryMapper;
import com.bst.etl.service.IDwQueryService;
import com.bst.etl.vo.DwQueryVO;
import com.bst.common.vo.HeaderAndBodyVO;
import com.bst.md.domain.MdMedPubfld;
import com.bst.md.service.IMdMedPubfldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DwQueryServiceImpl implements IDwQueryService {

    @Autowired
    DwQueryMapper dwQueryMapper;
    @Autowired
    IMdMedPubfldService mdMedPubfldService;

    @Override
    public AjaxResult findDwDataWinthHeader(DwQueryVO queryVO) {
        List<Map<String,Object>> dataList = this.queryFromDw(queryVO);
        Map<String,String> header = new LinkedHashMap<>();
        if(dataList.size()>0) {
            List<String> idPubfldList = new ArrayList<>();
            for(String key:dataList.get(0).keySet()) {
                idPubfldList.add(key);
            }
            List<MdMedPubfld> pubfldList = mdMedPubfldService.findByIdList(idPubfldList);
            if(pubfldList.size()>0) {
                header = pubfldList.stream().collect(Collectors.toMap(MdMedPubfld::getIdPubfld,MdMedPubfld::getNa));
            }
            Object time;String timeDes;
            for (Map<String, Object> map : dataList) {
                time = map.get("ID_DIM_TIME_OCCUR");
                if(time!=null) {
                    timeDes = time.toString().replaceAll("(.{2})", "$1:");
                    map.put("ID_DIM_TIME_OCCUR",timeDes.substring(0,timeDes.length()-1));
                }
            }
        }
        HeaderAndBodyVO headerAndBodyVO = new HeaderAndBodyVO();
        headerAndBodyVO.setThead(header);
        headerAndBodyVO.setTbody(dataList);
        return AjaxResult.success(headerAndBodyVO);
    }

    @Override
    @DataSource(value= JobConstant.DB_CLS_DW)
    public List<Map<String,Object>> queryFromDw(DwQueryVO queryVO) {
        List<Map<String,Object>> dataList = dwQueryMapper.queryDwData(queryVO);
        return dataList;
    }

}
